<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

</head>

<body>
    <div class="box">
        <h3>省市区三级联动</h3>

        <div class="content">
            <select name="" id="sel_p">
                <option value="">请选择省</option>
            </select>
            <select name="" id="sel_c">
                <option value="">请选择市</option>
            </select>
            <select name="" id="sel_a">
                <option value="">请选择区</option>
            </select>
        </div>
    </div>


    <script src="./js/jquery-1.12.2.js"></script>
    <script src="./js/template-web.js"></script>

    <script type="text/template" id="p_temp">
        {{each data value index}}
            <option value="{{value.id}}" >{{value.text}}</option>
        {{/each}}
    </script>
    <script>
        // 进入页面时请求省份
        fetch('/province', {
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => {
            return res.json()
        }).then(res => {
            console.log(res);
                let html = template('p_temp', {data: res.data});
                console.log(html);
                
                $('#sel_p').html(html)
        })
        // 当用户点击某一省份时 请求相应的市
        // console.log($('#sel_p option:selected'));

        $('#sel_p').on('change', function () {
            // console.log($(this).val());
            let p_id = $(this).val();
            $.ajax({
                url: "./city",
                data: {
                    p_id: p_id
                },
                success: (res) => {
                    // console.log(res);
                    let html = template('p_temp', {
                        data: res.data
                    })
                    $('#sel_c').append(html)
                }
            })
        })

        // 当用户点击某一市时 请求相应的区
        $('#sel_c').on('change', function () {
            // console.log($(this).val());
            let c_id = $(this).val();
            $.ajax({
                url: "./area",
                data: {
                    c_id: c_id
                },
                success: (res) => {
                    // console.log(res);
                    let html = template('p_temp', {
                        data: res.data
                    })
                    $('#sel_a').append(html)
                }
            })
        })
    </script>
</body>

</html>